package com.ruoyi.framework.wx.handle;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wx.domain.WxApp;
import com.ruoyi.wx.service.IWxAppService;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Component
public class SubscribeHandler implements WxMpMessageHandler {
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
    private IWxAppService wxAppService;
	
	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException {
		String lang = "zh_CN";
		String wxId = wxMessage.getToUser();
		WxMpUser user = wxMpService.getUserService().userInfo(wxMessage.getFromUser(), lang);
		String content = "欢迎关注";
		if(StringUtils.isNotBlank(user.getUnionId())){
			List<SysUser> userList = sysUserService.getUserByUnionId(wxId,user.getUnionId());
			
			Boolean flag = true;
			if(CollectionUtils.isEmpty(userList)){
				flag = false;
			}
			
			for(SysUser sysUser : userList){
				sysUser.setWxOpenId(user.getOpenId());
				sysUser.setIsWelcome(1);
				sysUserService.updateById(sysUser);
			}
			
			if(flag){
				try {
					SysUser su = userList.get(0);
					String title = "注册成功，赠送400趣豆，祝你早日脱单，点击进入";
					WxApp app = wxAppService.getByAppid(su.getAppId());
					if("1".equals(app.getStatus())){
						title = "注册成功，赠送一天会员，祝你早日脱单，点击进入";
					}
					
					
					//SysUser ru = sysUserService.getRandomUserByUser(su);
					String pagePath = "pages/index";
					/*if(ru != null){
						pagePath = pagePath + "?userId="+ru.getUserId();
					}*/
					// 发送小程序
					//获取素材库相关实现
					WxMpMaterialService materialService = wxMpService.getMaterialService();
					//上传临时素材
					InputStream inputStream = IoUtil.toStream(HttpUtil.downloadBytes("http://rbtnet.oss-cn-hangzhou.aliyuncs.com/test/20220914/58242695c2a8421b892eced5f1bd3b15.jpeg"));
					WxMediaUploadResult wxMediaUploadResult = materialService.mediaUpload(WxConsts.KefuMsgType.IMAGE, ".jpg", inputStream);
					//获取素材ID
					String mediaId = wxMediaUploadResult.getMediaId();
					wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage
							.MINIPROGRAMPAGE()
							.title(title)
							.toUser(wxMessage.getFromUser())
							.thumbMediaId(mediaId)
							.appId(su.getAppId())
							.pagePath(pagePath)
							.build());
					
					
					
					/*if("gh_b0cfae9edc73".equals(wxId)){
						//上传临时素材
						inputStream = IoUtil.toStream(HttpUtil.downloadBytes("http://rbtnet.oss-cn-hangzhou.aliyuncs.com/60df874fcf2c7b030bb56fb2174c5be7.jpg"));
						wxMediaUploadResult = materialService.mediaUpload(WxConsts.KefuMsgType.IMAGE, ".jpg", inputStream);
						mediaId = wxMediaUploadResult.getMediaId();
						wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage
								.MINIPROGRAMPAGE()
								.title("新人领券抽手机福利，点击进入")
								.toUser(wxMessage.getFromUser())
								.thumbMediaId(mediaId)
								.appId("wxa849d2039ababe39")
								.build());
					}*/
				} catch (Exception e) {
					e.printStackTrace();
				}
			
			}else{
				String pagePath = "pages/index";
				// 发送小程序
				//获取素材库相关实现
				WxMpMaterialService materialService = wxMpService.getMaterialService();
				//上传临时素材
				InputStream inputStream = IoUtil.toStream(HttpUtil.downloadBytes("http://rbtnet.oss-cn-hangzhou.aliyuncs.com/test/20220914/58242695c2a8421b892eced5f1bd3b15.jpeg"));
				WxMediaUploadResult wxMediaUploadResult = materialService.mediaUpload(WxConsts.KefuMsgType.IMAGE, ".jpg", inputStream);
				//获取素材ID
				String mediaId = wxMediaUploadResult.getMediaId();
				wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage
						.MINIPROGRAMPAGE()
						.title("注册成功，祝你早日脱单，点击进入")
						.toUser(wxMessage.getFromUser())
						.thumbMediaId(mediaId)
						.appId("wx4a8ce56c55215ee0")
						.pagePath(pagePath)
						.build());
				return WxMpXmlOutMessage.TEXT().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
						.content(content).build();
			}
			
		}
		
		return WxMpXmlOutMessage.TEXT().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
				.content(content).build();
	}
	
	

}
